package org.logan.sample.web.base.shiro;

import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.logan.sample.db.model.SysResource;
import org.logan.sample.db.model.SysUser;
import org.logan.sample.web.main.service.system.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录验证（shiro框架）
 * @author Auser
 */
@Component
public class LoginAuthRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(LoginAuthRealm.class);
    @Autowired
    private SysUserService      userService;

    public LoginAuthRealm() {
        super();
        // 设置认证token的实现类
        setAuthenticationTokenClass(UsernamePasswordToken.class);
    }

    // 授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
        // 获取当前登录的用户
        SysUser user = (SysUser) super.getAvailablePrincipal(principals);
        List<SysResource> menus = user.getMenus();
        // 资源菜单授权认证
        for (SysResource SysResource : menus) {
            if (SysResource.getResourceParentId() != 0 && !StringUtils.isBlank(SysResource.getResourceUrl()) && SysResource.getResourceIsEnable() == 1) {
                result.addStringPermission("/" + SysResource.getResourceUrl());
            } else {
                for (SysResource childrens : SysResource.getChildrens()) {
                    if (StringUtils.equals(childrens.getResourceParentId().toString(), SysResource.getResourceId().toString())
                            && !StringUtils.isBlank(childrens.getResourceUrl()) && childrens.getResourceIsEnable() == 1) {
                        result.addStringPermission("/" + childrens.getResourceUrl());
                    }
                }
            }
        }
        // TODO 权限（按钮级别）授权认证
        return result;
    }

    // 认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        try {
            UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
            String username = token.getUsername();
            SysUser user = null;
            try {
                user = userService.getByUserName(token.getUsername());
            } catch (Exception e) {
                logger.error("用户【" + token.getUsername() + "】登录异常！", e);
                throw new AccountException("登录异常！");
            }
            if (StringUtils.isNotBlank(username)) {
                if (user == null) {
                    throw new AccountException("账号不存在！");
                } else if (user.getUserStatus() == 0) {
                    throw new AccountException("账号未激活，请联系客服！");
                } else if (user.getUserStatus() == 1) {
                    return new SimpleAuthenticationInfo(user, user.getUserPassword(), getName());
                } else {
                    throw new AccountException("登录失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
